--
-- Author: shineflag
-- Date: 2017-09-08 16:31:03
--

local skynet = require "skynet"
local log = require("log")
local cluster = require("skynet.cluster")

local TAG = "LOG_CENTER"

local cluster_log = "cluster_logcenter"

local logcenter_proxy

--收到fname相关的日志时，转发给 addr1 addr2
local redirect = {
	-- [fname] = {addr1, addr2}
}



local function connect_center()
	local logcenter = cluster.query(cluster_log, "logcenter")
	logcenter_proxy = cluster.proxy(cluster_log, logcenter)
	log.d(TAG, "logcenter:%s proxy:%s", logcenter,logcenter_proxy)
end



CMD = {}
--[[
--	@desc 将字符串记录到文件
--  @param fname 文件名称
--  @param msg  具体的日志信息
]]
function CMD.record(fname,msg)
	if not logcenter_proxy then 
		local ok = pcall(connect_center)
		if not ok then 
			log.d(TAG,"connect alloc proxy error")
			return 
		end
	end

	local ok , info = pcall(skynet.call, logcenter_proxy, "lua", "record", fname, msg)
	if not ok then 
		log.d(TAG,"failefname[%s] msg[%s]")
		logcenter_proxy = nil 
		return 
	end

end

--注册转发消息 当有用户注册时会以 rlog 转发给注册的地址
function CMD.regist(fname, cname, addr)
	redirect[fname] = redirect[fname] or {}
	table.insert(redirect[fname], addr)
	local ok , info = pcall(skynet.call, logcenter_proxy, "lua", "regist", fname, cname)
	if not ok then 
		log.d(TAG,"regist fname[%s] cname[%s] [%x]failed",fname, cname, addr)
		logcenter_proxy = nil 
		return 
	end
end

function CMD.rlog(fname, msg)
	if redirect[fname] then 
		for _, addr in pairs(redirect[fname]) do
			skynet.send(addr, "lua", "rlog", fname,msg)
		end
	end
end


skynet.start(function()
	cluster.register("logagent")
	connect_center()
	skynet.dispatch("lua", function( session,address, cmd,... )
		local f = CMD[cmd]
		if f then
			if session ~= 0 then
		   		skynet.ret(skynet.pack( f(...) ) )
		   	else
		   		f(...)
		   	end 
		else
		    log.e(TAG,string.format("address[%d] call not exist cmd[%s] ",address,cmd) )
	    end
	end)
end)